<template>
  <div>
      <MyFormCreate v-model="searchForm" :rule="searchFormRules" :key="key">
        <template #field-createdAt="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%" v-model="searchForm.createdAt"
              :teleported="false" @change="dateChange" />
          </el-form-item>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <!-- <div>
        <sj-button type="primary" :icon="Plus" @click="add">添加</sj-button>
        <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button>
      </div> -->
      <pure-table class="" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
         @selection-change="selectionChange" :isShowPag="false">
        <template #belong="{ row }">
          {{ isNullOrEmpty(row?.useType == 1 ? '项目 -' : row?.useType == 2 ? '家庭 -' : '') }}
          {{ isNullOrEmpty(row?.useTypeName) }}
        </template>
        <template #confirm="{ row }">
          <el-tag :type="CONFIRMSTATUSTEXT[row.confirm]?.type" :key="row.confirm">
            {{ CONFIRMSTATUSTEXT[row.confirm]?.label }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="info(row)">详情</sj-link>
            <sj-link v-if="row.confirm == -1" custom-type="sblue" :underline="false"
              @click="alarmHandling(row)">处理</sj-link>
            <!-- <sj-link custom-type="sblue" :underline="false" @click="edit(row)">编辑</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link> -->
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
  </div>
</template>
<script lang="ts" setup>

import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/large-data-screen/component/supervise-alarm/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import { CONFIRMSTATUS, ALARMTYPE, CONFIRMSTATUSTEXT } from "@/constant/alarm-mangenment";
import { alarmHandling } from '../../utils/index'


const props = defineProps({
  defaultSearch: {
    type: Object,
    default: null
  }
})
const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'deviceSN', title: titles.deviceSN, value: null, props: {
      placeholder: prompt.deviceSN, clearable: true
    }
  },
  {
    type: 'input', field: 'alarmTitle', title: titles.alarmTitle, value: null, props: {
      placeholder: prompt.alarmTitle, clearable: true
    }
  },
  {
    type: 'input', field: 'projectName', title: titles.projectName, value: null, props: {
      placeholder: prompt.projectName, clearable: true
    }
  },
  {
    type: 'select', field: 'confirm', title: titles.confirm, value: null,
    options: CONFIRMSTATUS,
    props: {
      placeholder: prompt.confirm, clearable: true, teleported: false
    }
  },
  {
    type: "fieldComponent", field: "createdAt", title: titles.createdAt, value: null,
    props: {
      placeholder: prompt.createdAt,
      clearable: true
    }
  },
  {
    type: 'select', field: 'alarmType', title: titles.alarmType, value: null,
    options: ALARMTYPE,
    props: {
      placeholder: prompt.alarmType, clearable: true, teleported: false
    }
  },
  {
    type: 'select', field: 'productId', title: titles.productId, value: null, props: {
      placeholder: prompt.productId, clearable: true, teleported: false
    }
  },
  {
    type: 'input', field: 'nickname', title: titles.nickname, value: null, props: {
      placeholder: prompt.nickname, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  // { type: "selection", align: "left" },

  { prop: 'id', label: titles.id, width: 100, fixed: 'left' },
  { prop: 'belong', label: '设备归属' },
  // { prop: 'useType', label: titles.useType },
  // { prop: 'useTypeName', label: titles.useTypeName },
  { prop: 'productName', label: titles.productName, width: 150 },
  { prop: 'deviceSN', label: titles.deviceSN, width: 150 },
  { prop: 'alarmTitle', label: titles.alarmTitle, width: 150 ,showOverflowTooltip:true },
  { slot: 'confirm', label: titles.confirm, width: 100 },
  { prop: 'createdAt', label: titles.createdAt, width: 180 },
  { slot: 'action', label: titles.action, width: 150, fixed: 'right' },
];
onMounted(() => {
  if (props.defaultSearch) {
    let searchRule = searchFormRules.map(item => item.field)
    for (const key in props.defaultSearch) {
      if (!searchRule.includes(key)) {
        searchFormRules.push({ type: '', field: key, title: key, hidden: true })
      }
      searchForm.value[key] = props.defaultSearch[key];
    }
    key.value = Math.floor(Math.random() * 1000)
  }
  getTableList()
});
// 获取列表数据
const getTableList = () => {
  getList(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchForm.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `详情`,
    width: "800px",
    draggable: true,
    fullscreen: false,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    open({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "新增", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    open({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "新增") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const dateChange = e => {
  console.log(e);
  if (e) {
    searchForm.value.startTime = e[0];
    searchForm.value.endTime = e[1];
  } else {
    searchForm.value.startTime = '';
    searchForm.value.endTime = '';
  }
  getTableList()
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
